package models

import (
	"encoding/base64"
	"encoding/json"

	"github.com/gin-gonic/gin"
)

type ginCookie struct{}

func (cookie ginCookie) Set(c *gin.Context, key string, value interface{}) {
	bytes, _ := json.Marshal(value)
	desKey := []byte("itying.c") // key 必须为8字节
	encData, err := DesEncrypt(bytes, desKey)
	if err != nil {
		return
	}
	// ⚠️ 使用 Base64 编码后再写入 cookie，防止出现乱码或二进制数据损坏
	encStr := base64.StdEncoding.EncodeToString(encData)
	c.SetCookie(key, encStr, 3600*24*30, "/", c.Request.Host, false, true)
}

func (cookie ginCookie) Get(c *gin.Context, key string, obj interface{}) bool {
	valueStr, err := c.Cookie(key)
	if err == nil && valueStr != "" && valueStr != "[]" {
		desKey := []byte("itying.c")
		// ⚠️ Base64 解码
		crypted, err := base64.StdEncoding.DecodeString(valueStr)
		if err != nil {
			return false
		}
		decData, err := DesDecrypt(crypted, desKey)
		if err != nil {
			return false
		}
		err = json.Unmarshal(decData, obj)
		return err == nil
	}
	return false
}

func (cookie ginCookie) Remove(c *gin.Context, key string) bool {
	c.SetCookie(key, "", -1, "/", c.Request.Host, false, true)
	return true
}

var Cookie = &ginCookie{}
